package com.weike.bsp.service.impl

import com.weike.bsp.model.SimpleUser
import com.weike.bsp.model.UserDetailsInfo
import org.slf4j.LoggerFactory
import org.springframework.r2dbc.core.DatabaseClient
import org.springframework.security.core.userdetails.ReactiveUserDetailsService
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono

/**
 * 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails。
 * 该UserDetails包括用户名、密码、是否可用、是否过期等信息。
 *
 * @author lxb
 *
 * @see UserDetailsService
 *
 * @see org.springframework.security.provisioning.JdbcUserDetailsManager
 *
 */
@Service("userDetailsService")
class UserDetailsServiceImpl(
    private val databaseClient: DatabaseClient
) : ReactiveUserDetailsService {

    companion object {
        private val logger = LoggerFactory.getLogger(UserDetailsServiceImpl::class.java)
    }

    override fun findByUsername(username: String): Mono<UserDetails> {
        return databaseClient.sql("select * from pub_user where username = #{username}")
            .bind("username", username)
            .map(SimpleUser.Mapper())
            .first()
            .map {
                UserDetailsInfo(it)
            }
    }
}
